<?php

// Separate points by player, calculate total points, maximum number
// of games and keep ordered_list ordered by total
$player_total  = array();
$player_games  = array();
$ordered_list  = array();
foreach ($games as $game_id => $game)
{
  foreach ($game['points'] as $player_id => $point)
  {
    // Check if player modality is valid
    if ($players[$player_id]['modality'] != $modality) continue;
    
    if (!array_key_exists($player_id, $player_total))
    {
      $player_games[$player_id] = 0;
      $player_total[$player_id] = 0;
      $ordered_list[]           = $player_id;
    }

    // If player point bigger than 0, add to arrays
    if ($point['sum'] > 0)
    {
      $player_games[$player_id]++;
      $player_total[$player_id] += $point['sum'];

      // Keep ordered_list ordered by total
      $position = array_search($player_id, $ordered_list);
      while (--$position > -1 &&
             $player_total[$player_id] > $player_total[$ordered_list[$position]])
      {
        $ordered_list[$position+1] = $ordered_list[$position];
        $ordered_list[$position] = $player_id;
      }
    }
  }
}

?>

<table cellspacing="0" class="playerPointsTable">
  <tr>
    <th>Pos</th>
    <th>Nome</th>
    <th>Equipe</th>
<?php foreach ($games as $game): ?>
    <th><?php echo $game['place'] ?></th>
<?php endforeach; ?>
    <th>Média</th>
    <th>Total</th>
  </tr>

<?php foreach ($ordered_list as $key => $player_id): ?>
  <?php if ($key % 2 == 0): ?>
  <tr class="oddLine">
  <?php else: ?>
  <tr>
  <?php endif; ?>
    <td class="playerPosition"><?php echo ($key+1) ?></td>
    <td class="playerName"><?php echo $players[$player_id]['name'] ?></td>
    <td class="playerTeam"><?php echo $teams[$players[$player_id]['team_id']]['name'] ?></td>
  <?php foreach ($games as $game): ?>
    <td class="playerPoints">
    <?php
      if (array_key_exists($player_id, $game['points']))
        echo $game['points'][$player_id]['sum'];
      else
        echo "0";
    ?>
    </td>
  <?php endforeach; ?>
  <?php if ($player_games[$player_id] > 0): ?>
    <td class="playerPoints"><?php echo number_format($player_total[$player_id]/$player_games[$player_id], 5, ',', '.'); ?></td>
  <?php else: ?>
    <td class="playerPoints">0</td>
  <?php endif; ?>
    <td class="playerPoints"><?php echo $player_total[$player_id] ?></td>
  </tr>
<?php endforeach; ?>

</table>
